import React, { Component } from 'react'
import { Row, Button, Tabs, message } from 'antd'

import { Uploader } from 'antd-pro-toolkit'
import StandardTable from '@/components/StandardTable';

import styles from './Import.less'
import classNames from 'classnames';
import { connect } from 'dva';
const { TabPane } = Tabs;

@connect(({ loading }) => ({ importLoading: loading.effects['product/importSale'] || loading.effects['product/importSelf'], saveLoading: loading.effects['product/saveImportExcel'] }))
class Import extends Component {
  state = {
    file: {
      name: '请选择文件'
    },
    filePath: '',
    correctResult: [],
    incorrectResult: [],
    hasImport: false,
    key: '1',
    productType: ''
  }
  timeColumns = [
    {
      title: '始发地三字码',
      dataIndex: 'startPlace',
      render: this.renderTableCell('startPlace')
    },
    {
      title: '目的地三字码',
      dataIndex: 'endPlace',
      render: this.renderTableCell('endPlace')
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      render: this.renderTableCell('flightNo')
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      render: this.renderTableCell('flightDate')
    },
    {
      title: '计划起飞时间',
      dataIndex: 'startTime',
      render: this.renderTableCell('startTime')
    },
    {
      title: '计划落地时间',
      dataIndex: 'arriveTime',
      render: this.renderTableCell('arriveTime')
    },
    {
      title: '投放舱位量(kg)',
      dataIndex: 'weight',
      render: this.renderTableCell('weight')
    },
    {
      title: '成本单价(元/kg)',
      dataIndex: 'costUnitPrice',
      render: this.renderTableCell('costUnitPrice')
    },
    {
      title: '销售单价(元/kg)',
      dataIndex: 'saleUnitPrice',
      render: this.renderTableCell('saleUnitPrice')
    },
    {
      title: '起订量(kg)',
      dataIndex: 'startWeight',
      render: this.renderTableCell('startWeight')
    },
    {
      title: '收货时效(小时)',
      dataIndex: 'hours',
      render: this.renderTableCell('hours')
    },
    {
      title: '单件重量限制(<=N公斤/件)',
      dataIndex: 'weightLimit',
      render: this.renderTableCell('weightLimit')
    },
    {
      title: '货物类型',
      dataIndex: 'cargoTypes',
      render: this.renderTableCell('cargoType')
    },
    // {
    //   title: '单件尺寸限制(长/宽/高)cm',
    //   dataIndex: 'supplierName',
    //   render: this.renderTableCell('supplierId')
    // },
    {
      title: '资源提供方名称',
      dataIndex: 'supplierName',
      render: this.renderTableCell('supplierId')
    },
    {
      title: '服务商',
      dataIndex: 'operateSupplierName',
      render: this.renderTableCell('operateSupplier')
    },
    {
      title: '收货地址',
      dataIndex: 'address',
      render: this.renderTableCell('address')
    },
    {
      title: '联系电话',
      dataIndex: 'mobile',
      render: this.renderTableCell('mobile')
    }
  ]
  selfColumns = [
    {
      title: '始发地三字码',
      dataIndex: 'startPlace',
      render: this.renderTableCell('startPlace')
    },
    {
      title: '目的地三字码',
      dataIndex: 'endPlace',
      render: this.renderTableCell('endPlace')
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      render: this.renderTableCell('flightNo')
    },
    {
      title: '航班班期',
      dataIndex: 'periodList',
      render: this.renderTableCell('periodList')
    },
    {
      title: '计划起飞时间',
      dataIndex: 'startTime',
      render: this.renderTableCell('startTime')
    },
    {
      title: '计划落地时间',
      dataIndex: 'arriveTime',
      render: this.renderTableCell('arriveTime')
    },
    {
      title: '投放舱位量(kg)',
      dataIndex: 'weight',
      render: this.renderTableCell('weight')
    },
    {
      title: '货物类型',
      dataIndex: 'cargoTypes',
      render: this.renderTableCell('cargoType')
    },
    {
      title: '舱位生效日期',
      dataIndex: 'effectStartDate',
      render: this.renderTableCell('effectStartDate')
    },
    {
      title: '舱位失效日期',
      dataIndex: 'effectEndDate',
      render: this.renderTableCell('effectEndDate')
    },
    {
      title: '资源提供方名称',
      dataIndex: 'supplierName',
      render: this.renderTableCell('supplierId')
    },
  ]
  componentDidMount() {
    const { productType } = this.props;
    this.setState({ productType })
  }
  componentWillReceiveProps(nextProps) {
    const { productType, visible } = nextProps;
    this.setState({ productType })
    if (!visible) {
      this.reset()
    }
  }
  reset = () => {
    this.setState({
      file: {
        name: '请选择文件'
      },
      filePath: '',
      correctResult: [],
      incorrectResult: [],
      hasImport: false,
      key: '1',
      productType: ''
    })
  }
  renderTableCell(type) {
    return (text, record) => (
      <span className={this.checkData(type, record)}>
        {text ? text : record.errorMsg[type]}
      </span>
    );
  }
  checkData(type, record) {
    if (1 === record.status) {
      return '';
    }
    if (record.errorMsg[type]) {
      return styles.errorData;
    }
    return '';
  }
  handleChange = (file) => {
    this.setState({
      file: file[0],
      filePath: file[0].path
    });
  }
  handleExport = () => {
    const { dispatch, importLoading } = this.props;
    if (importLoading) return
    const { productType, filePath } = this.state;
    let type = productType === 'time' ? 'product/importSale' : 'product/importSelf'
    dispatch({
      type,
      payload: {
        queryParams: {
          filePath
        }
      }
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.setState({ correctResult: data.filter(item => item.status !== 0), incorrectResult: data.filter(item => item.status === 0), hasImport: true })
      }
    })
  }
  onTabChange = key => {
    this.setState({ key });
  };

  renderTable = (list, key) => {
    const { saveLoading } = this.props;
    const { productType } = this.state
    return (
      <>
        <StandardTable
          rowKey="index"
          bordered
          pagination={false}
          data={{ list, pagination: {} }}
          columns={productType === 'time' ? this.timeColumns : this.selfColumns}
        />
        {
          key === '1' &&
          <div style={{ marginTop: 20 }}>
            <Button onClick={this.handleSubmitImport} loading={saveLoading}>导入</Button>
          </div>
        }
      </>
    )
  }
  handleSubmitImport = () => {
    const { dispatch, onChange, productType = 'today', nodeId, phaseId, saveLoading } = this.props;
    if (saveLoading) return
    const { correctResult } = this.state;
    dispatch({
      type: 'product/saveImportExcel',
      payload: {
        data: {
          nodeId,
          phaseId,
          productId: { today: '10000', tomorrow: '10001', time: '10002' }[productType],
          flightSaleDtoList: correctResult
        }
      }
    }).then(({ errorCode, data }) => {
      if (errorCode === 0) {
        this.reset()
        message.success('导入成功')
        if (onChange) {
          onChange()
        }
      }
    })
  }
  render() {
    const { file: { name = '请选择文件' }, filePath, incorrectResult, correctResult, hasImport, key, productType } = this.state;
    const { importLoading } = this.props;
    const importTemplateUrl = productType === 'time' ? '/api/v1/newFlight/downloadTemplateOnsale' : '/api/v1/newFlight/downloadTemplateSelf'

    return (
      <div className={styles.importResult}>
        {
          !hasImport &&
          <>
            <p><a href={importTemplateUrl}>下载《导入模板》</a></p>
            <Row type='flex'>
              <div className={
                classNames(styles.fileName, {
                  [styles.resultColor]: filePath
                })
              }>{name}</div>
              <Uploader
                uploadInfo={{ action: "/api/v1/sys/files/upload", accept: '.xls,.xlsx' }}
                placeholder='浏览'
                type="list"
                maxFileSize={8}
                showResult={false}
                alwaysShowUploadButton={true}
                style={{ display: 'inline-block' }}
                onChange={this.handleChange}
                max={1}
              />
            </Row>
            <div style={{ marginTop: 20 }}>
              <Button onClick={this.handleExport} disabled={!filePath} loading={importLoading}>下一步</Button>
            </div>
          </>
        }
        {
          hasImport && (
            <Tabs activeKey={key} onChange={this.onTabChange}>
              <TabPane forceRender={true} tab={`正确(${correctResult.length})`} key="1">
                {'1' === key && this.renderTable(correctResult, '1')}
              </TabPane>
              <TabPane forceRender={true} tab={`错误(${incorrectResult.length})`} key="0">
                {'0' === key && this.renderTable(incorrectResult, '0')}
              </TabPane>
            </Tabs>
          )
        }

      </div>
    )
  }
}

export default Import
